#include <limits.h>		//PATH_MAX
#include <string.h>		//strcmp(), strcpy(), strcat()
#include <stdio.h>		//fprintf()
#include <stdlib.h>		//realpath()
#include <errno.h>		//strerror()

#include "stag.h"

#define GL_PATH_TO_WIN 1
#define GL_PATH_FROM_WIN 0


void path_build_path(const char *base, const char *part, char *storage)
	{
	strcpy(storage, base);
	if (base[strlen(base)-1]!=STAG_DIR_SEP[0]) strcat(storage, STAG_DIR_SEP);
	strcat(storage, part);
	return;
	}
	

void path_flip_slash(char *path, int direction)
	{
	int counter;
	char from, to;

	if (direction)
		{
		from='/';
		to='\\';
		}
	else
		{
		from='\\';
		to='/';		
		}
	
	for (counter=0; path[counter]!='\0'; counter++)
		{
		if (path[counter]==from) path[counter]=to;
		}
	
	return;
	}
	
int path_compare_bases(const char *filename)
	{
	char absPath[PATH_MAX];
	realpath(filename, absPath);
	
	if (strncmp(absPath, stagBaseDir, strlen(stagBaseDir))!=0)
		{
		fprintf(stderr, "Error: File \"%s\" is not a sub-directory of the base directory %s.\n", absPath, stagBaseDir);
		return 0;
		}

	return 1;	
	}	

char* path_get_relative_path(const char *filename)
	{
	int offset, counter;
	static char newPath[PATH_MAX];

	offset=strlen(stagBaseDir);
	if (!path_compare_bases(filename)) 
		{
		exit(1);
		}

	
	if ((realpath(filename, newPath))==NULL)
		{
		fprintf(stderr, "Error: File \"%s\" does not exist.\n", filename);
		exit(1);
		}
	
	for (counter=0; counter+offset<=strlen(newPath); counter++)
		{			
		newPath[counter]=newPath[offset+counter];
		}

	return newPath;
	}
